/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.PreexistingEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.ExporterItem;
import java.util.ArrayList;
import java.util.Collection;
import pojos.BillItem;
import pojos.Item;

/**
 *
 * @author A7med Kotb
 */
public class ItemJpaController implements Serializable {

    public ItemJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Item item) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (item.getExporterItemCollection() == null) {
            item.setExporterItemCollection(new ArrayList<ExporterItem>());
        }
        if (item.getBillItemCollection() == null) {
            item.setBillItemCollection(new ArrayList<BillItem>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<ExporterItem> attachedExporterItemCollection = new ArrayList<ExporterItem>();
            for (ExporterItem exporterItemCollectionExporterItemToAttach : item.getExporterItemCollection()) {
                exporterItemCollectionExporterItemToAttach = em.getReference(exporterItemCollectionExporterItemToAttach.getClass(), exporterItemCollectionExporterItemToAttach.getIdExporterItem());
                attachedExporterItemCollection.add(exporterItemCollectionExporterItemToAttach);
            }
            item.setExporterItemCollection(attachedExporterItemCollection);
            Collection<BillItem> attachedBillItemCollection = new ArrayList<BillItem>();
            for (BillItem billItemCollectionBillItemToAttach : item.getBillItemCollection()) {
                billItemCollectionBillItemToAttach = em.getReference(billItemCollectionBillItemToAttach.getClass(), billItemCollectionBillItemToAttach.getIdBillItem());
                attachedBillItemCollection.add(billItemCollectionBillItemToAttach);
            }
            item.setBillItemCollection(attachedBillItemCollection);
            em.persist(item);
            for (ExporterItem exporterItemCollectionExporterItem : item.getExporterItemCollection()) {
                Item oldItemIDOfExporterItemCollectionExporterItem = exporterItemCollectionExporterItem.getItemID();
                exporterItemCollectionExporterItem.setItemID(item);
                exporterItemCollectionExporterItem = em.merge(exporterItemCollectionExporterItem);
                if (oldItemIDOfExporterItemCollectionExporterItem != null) {
                    oldItemIDOfExporterItemCollectionExporterItem.getExporterItemCollection().remove(exporterItemCollectionExporterItem);
                    oldItemIDOfExporterItemCollectionExporterItem = em.merge(oldItemIDOfExporterItemCollectionExporterItem);
                }
            }
            for (BillItem billItemCollectionBillItem : item.getBillItemCollection()) {
                Item oldItemIDOfBillItemCollectionBillItem = billItemCollectionBillItem.getItemID();
                billItemCollectionBillItem.setItemID(item);
                billItemCollectionBillItem = em.merge(billItemCollectionBillItem);
                if (oldItemIDOfBillItemCollectionBillItem != null) {
                    oldItemIDOfBillItemCollectionBillItem.getBillItemCollection().remove(billItemCollectionBillItem);
                    oldItemIDOfBillItemCollectionBillItem = em.merge(oldItemIDOfBillItemCollectionBillItem);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findItem(item.getIdItem()) != null) {
                throw new PreexistingEntityException("Item " + item + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Item item) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Item persistentItem = em.find(Item.class, item.getIdItem());
            Collection<ExporterItem> exporterItemCollectionOld = persistentItem.getExporterItemCollection();
            Collection<ExporterItem> exporterItemCollectionNew = item.getExporterItemCollection();
            Collection<BillItem> billItemCollectionOld = persistentItem.getBillItemCollection();
            Collection<BillItem> billItemCollectionNew = item.getBillItemCollection();
            Collection<ExporterItem> attachedExporterItemCollectionNew = new ArrayList<ExporterItem>();
            for (ExporterItem exporterItemCollectionNewExporterItemToAttach : exporterItemCollectionNew) {
                exporterItemCollectionNewExporterItemToAttach = em.getReference(exporterItemCollectionNewExporterItemToAttach.getClass(), exporterItemCollectionNewExporterItemToAttach.getIdExporterItem());
                attachedExporterItemCollectionNew.add(exporterItemCollectionNewExporterItemToAttach);
            }
            exporterItemCollectionNew = attachedExporterItemCollectionNew;
            item.setExporterItemCollection(exporterItemCollectionNew);
            Collection<BillItem> attachedBillItemCollectionNew = new ArrayList<BillItem>();
            for (BillItem billItemCollectionNewBillItemToAttach : billItemCollectionNew) {
                billItemCollectionNewBillItemToAttach = em.getReference(billItemCollectionNewBillItemToAttach.getClass(), billItemCollectionNewBillItemToAttach.getIdBillItem());
                attachedBillItemCollectionNew.add(billItemCollectionNewBillItemToAttach);
            }
            billItemCollectionNew = attachedBillItemCollectionNew;
            item.setBillItemCollection(billItemCollectionNew);
            item = em.merge(item);
            for (ExporterItem exporterItemCollectionOldExporterItem : exporterItemCollectionOld) {
                if (!exporterItemCollectionNew.contains(exporterItemCollectionOldExporterItem)) {
                    exporterItemCollectionOldExporterItem.setItemID(null);
                    exporterItemCollectionOldExporterItem = em.merge(exporterItemCollectionOldExporterItem);
                }
            }
            for (ExporterItem exporterItemCollectionNewExporterItem : exporterItemCollectionNew) {
                if (!exporterItemCollectionOld.contains(exporterItemCollectionNewExporterItem)) {
                    Item oldItemIDOfExporterItemCollectionNewExporterItem = exporterItemCollectionNewExporterItem.getItemID();
                    exporterItemCollectionNewExporterItem.setItemID(item);
                    exporterItemCollectionNewExporterItem = em.merge(exporterItemCollectionNewExporterItem);
                    if (oldItemIDOfExporterItemCollectionNewExporterItem != null && !oldItemIDOfExporterItemCollectionNewExporterItem.equals(item)) {
                        oldItemIDOfExporterItemCollectionNewExporterItem.getExporterItemCollection().remove(exporterItemCollectionNewExporterItem);
                        oldItemIDOfExporterItemCollectionNewExporterItem = em.merge(oldItemIDOfExporterItemCollectionNewExporterItem);
                    }
                }
            }
            for (BillItem billItemCollectionOldBillItem : billItemCollectionOld) {
                if (!billItemCollectionNew.contains(billItemCollectionOldBillItem)) {
                    billItemCollectionOldBillItem.setItemID(null);
                    billItemCollectionOldBillItem = em.merge(billItemCollectionOldBillItem);
                }
            }
            for (BillItem billItemCollectionNewBillItem : billItemCollectionNew) {
                if (!billItemCollectionOld.contains(billItemCollectionNewBillItem)) {
                    Item oldItemIDOfBillItemCollectionNewBillItem = billItemCollectionNewBillItem.getItemID();
                    billItemCollectionNewBillItem.setItemID(item);
                    billItemCollectionNewBillItem = em.merge(billItemCollectionNewBillItem);
                    if (oldItemIDOfBillItemCollectionNewBillItem != null && !oldItemIDOfBillItemCollectionNewBillItem.equals(item)) {
                        oldItemIDOfBillItemCollectionNewBillItem.getBillItemCollection().remove(billItemCollectionNewBillItem);
                        oldItemIDOfBillItemCollectionNewBillItem = em.merge(oldItemIDOfBillItemCollectionNewBillItem);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = item.getIdItem();
                if (findItem(id) == null) {
                    throw new NonexistentEntityException("The item with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Item item;
            try {
                item = em.getReference(Item.class, id);
                item.getIdItem();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The item with id " + id + " no longer exists.", enfe);
            }
            Collection<ExporterItem> exporterItemCollection = item.getExporterItemCollection();
            for (ExporterItem exporterItemCollectionExporterItem : exporterItemCollection) {
                exporterItemCollectionExporterItem.setItemID(null);
                exporterItemCollectionExporterItem = em.merge(exporterItemCollectionExporterItem);
            }
            Collection<BillItem> billItemCollection = item.getBillItemCollection();
            for (BillItem billItemCollectionBillItem : billItemCollection) {
                billItemCollectionBillItem.setItemID(null);
                billItemCollectionBillItem = em.merge(billItemCollectionBillItem);
            }
            em.remove(item);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Item> findItemEntities() {
        return findItemEntities(true, -1, -1);
    }

    public List<Item> findItemEntities(int maxResults, int firstResult) {
        return findItemEntities(false, maxResults, firstResult);
    }

    private List<Item> findItemEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Item.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Item findItem(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Item.class, id);
        } finally {
            em.close();
        }
    }

    public int getItemCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Item> rt = cq.from(Item.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
